from __future__ import print_function

import dbase
from os.path import expanduser, getsize, abspath, exists, dirname, isdir, basename
from os import getcwd, makedirs, remove, walk, stat, link, symlink, unlink, system
import logging
import string
import ConfigParser
import utils

def init(cwd):
	## If init has been requested, process it before doing anything else
	projectName = None
	while projectName == None:
		projectName = raw_input("Project/friendly name: ")
	
	configFile = raw_input("Specifiy config file [{}/config/pdrive.{}.conf]: ".format(cwd, projectName))
	if string.strip(configFile) == "":
		configFile = "{}/config/pdrive.{}.conf".format(cwd, projectName)

	dbaseFile = raw_input("Specify dbase path file [{}/dbase/pdrive.{}.sqlite3]: ".format(cwd, projectName))
	if string.strip(dbaseFile) == "":
		dbaseFile = "{}/dbase/pdrive.{}.sqlite3".format(cwd, projectName)

	importPath = raw_input("Specify root path of files to import [{}/import]: ".format(cwd))
	if string.strip(importPath) == "":
		importPath = "{}/import".format(cwd)

	logFile = raw_input("Specify path of log file [{}/log/{}.log]: ".format(cwd, projectName))
	if string.strip(logFile) == "":
		logFile = "{}/log/{}.log".format(cwd, projectName)

	logLevel = "zz"
	while string.lower(logLevel) not in ['info','warn','error','crit','error','debug']:
		logLevel = raw_input("Specify log level (info|warn|error|crit|error|debug) [info]: ")
		if string.strip(logLevel) == "":
			logLevel = "info"

	configPathDir = dirname(configFile)
	if not exists(configPathDir):
		makedirs(configPathDir)

	dbasePathDir = dirname(dbaseFile)
	if not exists(dbasePathDir):
		makedirs(dbasePathDir)

	logPathDir = dirname(logFile)
	if not exists(logPathDir):
		makedirs(logPathDir)

	if not exists(importPath):
		makedirs(importPath)
	
	config = ConfigParser.SafeConfigParser()
	config.add_section("pdrive")
	config.set("pdrive", "projectName", projectName)
	config.set("pdrive", "dbase", dbaseFile)
	config.set("pdrive", "logFile", logFile)
	config.set("pdrive", "logLevel", logLevel)
	config.set("pdrive", "importPath", importPath)
	config.set("pdrive", "lighttpdSocket", "")
	with open(configFile, "wb") as configFP:
		config.write(configFP)

	if exists(dbaseFile):
		deleteDbase = None
		while deleteDbase not in ["YES", "NO"]:
			deleteDbase = raw_input("The dbase file {} already exists. Do you want to delete it? ('YES' or 'NO'): ".format(dbaseFile))
		if deleteDbase == "YES":
			remove(dbaseFile)
		else:
			print("DBase file will be left untouched. My work is done")
			print("Perhaps you should import some files... rerun pdrive with 'media import'")
			raise SystemExit
	
	try:
		db = dbase.DBase(dbaseFile)
	except dbase.CantConnect as e:
		print("Cannot connect to sqlite database file ({}): {}".format(sqliteDbaseFile, e))
		raise SystemExit

	if db.initDbase():
		pdriveRoot = None
		while pdriveRoot is None:
			pdriveRoot = raw_input("Specify the root directory [{}]: ".format(cwd))
			if string.strip(pdriveRoot) == "":
				pdriveRoot = cwd
		if not exists(pdriveRoot):
			makedirs(pdriveRoot)

		pdriveFiles = None
		while pdriveFiles is None:
			pdriveFiles = raw_input("Speficy the file repository directory [{}/files]: ".format(pdriveRoot))
			if string.strip(pdriveFiles) == "":
				pdriveFiles = "{}/files".format(pdriveRoot)
		if not exists(pdriveFiles):
			makedirs(pdriveFiles)
		
		db.setKeyValue("pdrive_root", pdriveRoot)
		db.setKeyValue("pdrive_files", pdriveFiles)
		db.setKeyValue("pdrive_friendly_name", projectName)
		
		db.setKeyValue("aws_id", raw_input("AWS ID ([enter] for none/skip): "))
		db.setKeyValue("aws_key", raw_input("AWS Key ([enter] for none/skip): "))
		db.setKeyValue("aws_s3_bucket", raw_input("AWS S3 Bucket ([enter] for none/skip): "))
		db.setKeyValue("aws_s3_objectPrefix", raw_input("AWS S3 Object Prefix (ex: mypDriveStuff/) ([enter] for none/skip): "))
		db.setKeyValue("aws_s3_encrypt", raw_input("S3 Server Side Encyption ([enter] for none/skip, 1 = yes, 0 = no): "))
		db.setKeyValue("aws_s3_reducedRedun", raw_input("S3 Storage Reduced Redundancy ([enter] for none/skip, 1 = yes, 0 = no): "))
		db.setKeyValue("video_viewer", raw_input("Video Viewer ([enter] for none/skip): "))
		db.setKeyValue("image_viewer", raw_input("Image Viewer ([enter] for none/skip): "))
		print ("Database has been initialized. Now, go import some files! 'pdrive media import'")
	else:
		print("Failed to initialize the database...")
	raise SystemExit
